package br.sed.theenemy.business.utils;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.validator.Field;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.FieldChecks;
import org.apache.struts.validator.Resources;

public class XssValidator implements Serializable {

    private static final long serialVersionUID = 7663907764781892662L;

    /**
     * Check is a string contains HTML or JS code.
     * 
     * @param bean      The bean validation is being performed on.
     * @param va        The <code>ValidatorAction</code> that is currently
     *                  being performed.
     * @param field     The <code>Field</code> object associated with the
     *                  current field being validated.
     * @param errors    The <code>ActionMessages</code> object to add errors
     *                  to if any validation errors occur.
     * @param validator The <code>Validator</code> instance, used to access
     *                  other field values.
     * @param request   Current request object.
     * @return true if meets stated requirements, false otherwise.
     */
    public static boolean validateXssAttack(Object bean, ValidatorAction va,
            Field field, ActionMessages errors, Validator validator,
            HttpServletRequest request) {

        String value = null;
        if (isString(bean)) {
            value = (String) bean;
        } else {
            value = ValidatorUtils.getValueAsString(bean, field.getProperty());
        }
        
        if (AvoidXss.isPossibleXssAttack(value)) {
            errors.add(field.getKey(),
                    Resources.getActionMessage(validator, request, va, field));
            
            return false;
        }
        
        return true;
    }

    /**
     * @see FieldChecks#isString(Object)
     * 
     * @param o
     * @return
     */
    private static boolean isString(Object o) {
        return (o == null) ? true : String.class.isInstance(o);
    }

}
